package com.china08.yxyapi.api.manage.edu.platform.statistics.resourcepandect1;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.aggregation.SkipOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceMonth;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceReport;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceWeekOfYearReport;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;

/**
 * 
 * @Description 资源统计列表-按市（省下的数据）
 *
 * @Author LiuWeidong
 *
 * @Date 2017年12月18日
 *
 */
@CrossOrigin
@RestController
public class ResourceCountCityListController extends YxyApiBaseController {

    @Autowired
    private MongoTemplate mt;

    @RequestMapping(value = "/api_yw/manage/edu/platform/statistics/resourcepandect1/city/list/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {

        String areaIdProvince = getProfile(request, response).getSchoolAreaIdProvince();
        String keyWord = reqModel.keyWord;
        Integer month = reqModel.month;
        Integer week = reqModel.week;
        Integer year = reqModel.year;
        Integer resOrder = reqModel.resOrder;
        Integer shareResOrder = reqModel.shareResOrder;
        Integer packOrder = reqModel.packOrder;
        Integer sharePackOrder = reqModel.sharePackOrder;

        // 排序
        Pageable pageable = null;
        if (resOrder != null && resOrder == 0) {
            pageable = reqModel.getPageable(Direction.DESC, "resCount");
        }
        if (resOrder != null && resOrder == 1) {
            pageable = reqModel.getPageable(Direction.ASC, "resCount");
        }
        if (shareResOrder != null && shareResOrder == 0) {
            pageable = reqModel.getPageable(Direction.DESC, "shareResCount");
        }
        if (shareResOrder != null && shareResOrder == 1) {
            pageable = reqModel.getPageable(Direction.ASC, "shareResCount");
        }

        if (packOrder != null && packOrder == 0) {
            pageable = reqModel.getPageable(Direction.DESC, "lectureCount");
        }
        if (packOrder != null && packOrder == 1) {
            pageable = reqModel.getPageable(Direction.ASC, "lectureCount");
        }
        if (sharePackOrder != null && sharePackOrder == 0) {
            pageable = reqModel.getPageable(Direction.DESC, "shareLectureCount");
        }
        if (sharePackOrder != null && sharePackOrder == 1) {
            pageable = reqModel.getPageable(Direction.ASC, "shareLectureCount");
        }

        List<RespModel> respModels = new ArrayList<RespModel>();

        Criteria criteria = new Criteria();

        AggregationResults<RespModel> groupCountResults = null;
        AggregationResults<RespModel> groupResults = null;
        Integer count = 0;

        // 无筛选条件
        if (month == null && week == null) {

            criteria.and("areaIdProvince").is(areaIdProvince);

            if (StringUtils.isNotBlank(keyWord)) {
                Pattern queryPattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
                criteria.and("areaNameCity").is(queryPattern);
            }

            TypedAggregation<SchoolUploadResourceReport> aggCount = Aggregation.newAggregation(SchoolUploadResourceReport.class, match(criteria), //
                    group("areaIdCity"));
            groupCountResults = mt.aggregate(aggCount, ResourceCountCityListController.RespModel.class);

            // 获取数据总数
            count = groupCountResults.getMappedResults().size();

            SkipOperation operation = new SkipOperation((pageable.getPageNumber() + 1 - 1) * pageable.getPageSize());
            LimitOperation limitOperation = new LimitOperation(pageable.getPageSize());
            SortOperation sortOperation = new SortOperation(pageable.getSort());

            TypedAggregation<SchoolUploadResourceReport> agg = Aggregation.newAggregation(SchoolUploadResourceReport.class, match(criteria), //
                    group("areaIdCity")//
                            .sum("lectureCount").as("lectureCount")//
                            .sum("shareLectureCount").as("shareLectureCount")//
                            .sum("resCount").as("resCount")//
                            .sum("shareResCount").as("shareResCount")//
                            .first("areaNameCity").as("areaNameCity"), //
                    sortOperation, operation, limitOperation//
            );
            groupResults = mt.aggregate(agg, ResourceCountCityListController.RespModel.class);

        }
        // 月
        else if (month != null && year == null && week == null) {

            criteria.and("areaIdProvince").is(areaIdProvince);

            if (StringUtils.isNotBlank(keyWord)) {
                Pattern queryPattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
                criteria.and("areaNameCity").is(queryPattern);
            }

            if (month != null) {
                criteria.and("intMonth").is(month);
            }

            TypedAggregation<SchoolUploadResourceMonth> aggCount = Aggregation.newAggregation(SchoolUploadResourceMonth.class, match(criteria), //
                    group("areaIdCity"));
            groupCountResults = mt.aggregate(aggCount, ResourceCountCityListController.RespModel.class);

            // 获取数据总数
            count = groupCountResults.getMappedResults().size();

            SkipOperation operation = new SkipOperation((pageable.getPageNumber() + 1 - 1) * pageable.getPageSize());
            LimitOperation limitOperation = new LimitOperation(pageable.getPageSize());
            SortOperation sortOperation = new SortOperation(pageable.getSort());

            TypedAggregation<SchoolUploadResourceMonth> agg = Aggregation.newAggregation(SchoolUploadResourceMonth.class, match(criteria), //
                    group("areaIdCity")//
                            .sum("lectureCount").as("lectureCount")//
                            .sum("shareLectureCount").as("shareLectureCount")//
                            .sum("resCount").as("resCount")//
                            .sum("shareResCount").as("shareResCount")//
                            .first("areaNameCity").as("areaNameCity"), //
                    sortOperation, operation, limitOperation//
            );
            groupResults = mt.aggregate(agg, ResourceCountCityListController.RespModel.class);

        }
        // 周的
        else {

            //
            criteria.and("areaIdProvince").is(areaIdProvince);

            if (StringUtils.isNotBlank(keyWord)) {
                Pattern queryPattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
                criteria.and("areaNameCity").is(queryPattern);
            }

            if (null != year && null != week) {
                criteria.and("year").is(year);
                criteria.and("week").is(week);
            }

            TypedAggregation<SchoolUploadResourceWeekOfYearReport> aggCount = Aggregation.newAggregation(SchoolUploadResourceWeekOfYearReport.class, match(criteria), //
                    group("areaIdCity"));
            groupCountResults = mt.aggregate(aggCount, ResourceCountCityListController.RespModel.class);

            // 获取数据总数
            count = groupCountResults.getMappedResults().size();

            SkipOperation operation = new SkipOperation((pageable.getPageNumber() + 1 - 1) * pageable.getPageSize());
            LimitOperation limitOperation = new LimitOperation(pageable.getPageSize());
            SortOperation sortOperation = new SortOperation(pageable.getSort());

            TypedAggregation<SchoolUploadResourceWeekOfYearReport> agg = Aggregation.newAggregation(SchoolUploadResourceWeekOfYearReport.class, match(criteria), //
                    group("areaIdCity")//
                            .sum("lectureCount").as("lectureCount")//
                            .sum("shareLectureCount").as("shareLectureCount")//
                            .sum("resCount").as("resCount")//
                            .sum("shareResCount").as("shareResCount")//
                            .first("areaNameCity").as("areaNameCity"), //
                    sortOperation, operation, limitOperation//
            );
            groupResults = mt.aggregate(agg, ResourceCountCityListController.RespModel.class);

        }

        //
        if (groupResults.getMappedResults() != null) {
            for (RespModel model : groupResults) {
                model.areaNameCity = model.areaNameCity;
                model.lectureCount = model.lectureCount;
                model.shareLectureCount = model.shareLectureCount;
                model.resCount = model.resCount;
                model.shareResCount = model.shareResCount;
                respModels.add(model);
            }

        }

        Page<RespModel> pageRes = new PageImpl<RespModel>(respModels, pageable, count);
        return pageRes;
    }

    /* 请求参数 */
    protected static class ReqModel extends YxyApiPageReqModel {

        // 选择月份(201705)
        public Integer month;
        // 选择周(选择周时需把当前年一起传过来)
        public Integer week;
        // 当前年
        public Integer year;
        // 搜索字段
        public String keyWord;

        // 资源数量排序 1正序0倒序
        public Integer resOrder;
        // 共享资源数排序 1正序0倒序
        public Integer shareResOrder;
        // 备课包排序 1正序0倒序
        public Integer packOrder;
        // 共享备课包排序 1正序0倒序
        public Integer sharePackOrder;

    }

    /* 响应参数 */
    protected static class RespModel extends YxyApiRespModel {

        // 市名称
        public String areaNameCity;
        // 资源数量
        public Long resCount;
        // 共享资源数量
        public Long shareResCount;
        // 备课包数量
        public Long lectureCount;
        // 共享备课包数量
        public Long shareLectureCount;

    }

}
